//
//  LoginVC.m
//  Doctor
//
//  Created by 阳光 on 16/9/10.
//  Copyright © 2016年 阳光. All rights reserved.
//  登录界面

#import "LoginVC.h"
#import "ResetPasswordVC.h"
#import "RegisterVC.h"

#import "DoctorInfoVC.h"
#import "ConfirmVC.h"
#import "TimeMainHomeVC.h"
#import "AppDelegate.h"
#import "QBMainVC.h"
#import "ReviewVC.h"

#import "NTESService.h"
#import "NTESLoginManager.h"


@interface LoginVC ()<CustomNavViewDelegate,RegisterVCDelegate>

@end


@implementation LoginVC

-(void)leftBtnEvent
{
    
}

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    self.navigationController.navigationBarHidden = NO;
}



-(void)rightBtnEvent
{
    //  跳转到注册界面
    RegisterVC *registerVC=[RegisterVC new];
    registerVC.delegate=self;
  [self presentViewController:registerVC animated:NO completion:nil];

}


-(void)registerToLoginWithUserName:(NSString *)userName password:(NSString *)password
{
    LeftTitle_TextFieldView *userNameView=(LeftTitle_TextFieldView *)[self.view viewWithTag:100];
    LeftTitle_TextFieldView *passwordView=(LeftTitle_TextFieldView *)[self.view viewWithTag:101];
    userNameView.textField.text=userName;
    passwordView.textField.text=password;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor=WhiteColor;
    
    [self initMainView];
}


-(void)initMainView
{
    CustomNavView *loginNavView=[[CustomNavView alloc]initWithTitle:NSLocalizedString(@"Log In", nil) leftBtnImage:nil hasLeftBtnImage:NO rightBtnTitle:NSLocalizedString(@"Sign Up", nil) hasRightBtnTitle:YES];//nitWithTitle:@"登录" leftBtnImage:nil hasLeftBtnImage:NO rightBtnTitle:@"注册" hasRightBtnTitle:YES];
    loginNavView.delegate=self;
    loginNavView.frame=CGRectMake(0,0,APPW,64);
    [self.view addSubview:loginNavView];
    
    // 用户名
    LeftTitle_TextFieldView *userNameView=[[LeftTitle_TextFieldView alloc]initWithTitle:NSLocalizedString(@"Username", nil) placeholder:NSLocalizedString(@"EnterName", nil)];//initWithTitle:@"用户名" placeholder:@"请输入用户名"];
    userNameView.tag=100;
    ViewBorderRadius(userNameView,kmargin/2,.5,ColorBDBDBD);
    [self.view addSubview:userNameView];
    [userNameView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(100);
        make.left.mas_equalTo(kmargin*3);
        make.size.mas_equalTo(CGSizeMake(APPW-kmargin*6,40));
    }];
    
    
    // 密码
    LeftTitle_TextFieldView *passwordView=[[LeftTitle_TextFieldView alloc]initWithTitle:NSLocalizedString(@"Password", nil) placeholder:NSLocalizedString(@"EnterPassword", nil)];//initWithTitle:@"密码" placeholder:@"请输入密码"];
    passwordView.tag=101;
    passwordView.textField.secureTextEntry=YES;
    ViewBorderRadius(passwordView,kmargin/2,.5,ColorBDBDBD);
    [self.view addSubview:passwordView];
    [passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
      make.top.mas_equalTo(userNameView.mas_bottom).offset(kmargin);
        make.left.mas_equalTo(kmargin*3);
        make.size.mas_equalTo(CGSizeMake(APPW-kmargin*6,40));
    }];
   
    
    // 登录
    UIButton *loginBtn=[UIButton new];
    [self.view addSubview:loginBtn];
    loginBtn.backgroundColor=Main_Color;
    loginBtn.titleLabel.font=Font_Number(16);
    ViewBorderRadius(loginBtn,kmargin/2,1,ClearColor);
    [loginBtn setTitle:NSLocalizedString(@"Log In", nil) forState:UIControlStateNormal];//@"登录"
    [loginBtn setTitleColor:WhiteColor forState:UIControlStateNormal];
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(passwordView.mas_bottom).offset(kmargin*2);
        make.size.mas_equalTo(CGSizeMake(APPW-kmargin*6,40));
        make.left.mas_equalTo(kmargin*3);
    }];
    [loginBtn addTarget:self action:@selector(loginBtnEvent) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIButton *forgetBtn=[UIButton new];
    [self.view addSubview:forgetBtn];
    [forgetBtn setTitle:NSLocalizedString(@"Forgot password", nil) forState:0];//@"忘记密码?"
    [forgetBtn setTitleColor:Color909090 forState:0];
    forgetBtn.titleLabel.font=Font_Number(11);
    [forgetBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(kmargin*3);
        make.top.mas_equalTo(loginBtn.mas_bottom).offset(kmargin*2);
    }];
    [forgetBtn addTarget:self action:@selector(forgetBtnEvent) forControlEvents:UIControlEventTouchUpInside];

}


-(void)forgetBtnEvent
{
    // 跳到修改密码界面
    ResetPasswordVC *resetPasswordVC=[ResetPasswordVC new];
  [self presentViewController:resetPasswordVC animated:NO completion:nil];
    
}


-(void)loginBtnEvent
{
    LeftTitle_TextFieldView *userNameView=(LeftTitle_TextFieldView *)[self.view viewWithTag:100];
    LeftTitle_TextFieldView *passwordView=(LeftTitle_TextFieldView *)[self.view viewWithTag:101];
    
    if (userNameView.textField.text.length==0)
    {
        [self.view makeToast:NSLocalizedString(@"Username cannot be empty", nil) duration:1.0 position:CSToastPositionCenter];//@"用户名不能为空"
    }
    else  if (passwordView.textField.text.length==0)
    {
        [self.view makeToast:NSLocalizedString(@"Password cannot be empty", nil) duration:1.0 position:CSToastPositionCenter];//@"密码不能为空"
    }
    else
    {
        NSDictionary *dic=@{
                            @"username":userNameView.textField.text,
                            @"password":passwordView.textField.text,
                            };
        
        [QBRequest LoginWithDic:dic Success:^(id res){
             
          [self.view makeToast:NSLocalizedString(@"Login Success", nil) duration:1.0 position:CSToastPositionCenter];//res[@"message"]
            
             NSDictionary *infoDic=res[@"info"];
             
             [Util saveObjectToUserDefault:infoDic[@"access_token"] forKey:@"access_token"];
             [Util saveObjectToUserDefault:infoDic[@"id"] forKey:@"id"];
             [Util saveObjectToUserDefault:dic[@"username"] forKey:@"username"];
             [Util saveObjectToUserDefault:infoDic[@"key"] forKey:@"key"];
             [Util saveObjectToUserDefault:infoDic[@"yuxin"] forKey:@"yuxin"];
             [Util saveObjectToUserDefault:infoDic[@"yuxin"][@"accid"] forKey:@"accid"];
             [Util saveObjectToUserDefault:infoDic[@"yuxin"][@"token"] forKey:@"token"];
             [Util saveObjectToUserDefault:infoDic forKey:@"info"];
             [Util saveObjectToUserDefault:infoDic[@"auth_status"] forKey:@"auth_status"];
             [Util saveObjectToUserDefault:infoDic[@"img"] forKey:@"img"];
            
             
             dispatch_after(dispatch_time(DISPATCH_TIME_NOW,(int64_t)(1.0*NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
             
                
                [self startSDKService];
                 
                 
                 // 判读当前医生所在有多少个医院,当有2个医院以上时,就显示医院列表界面,否则不显示
                 NSDictionary *dic=@{
                                     @"doctor_id":[Util getUserDefaultObjectForKey:@"id"]
                                     };
                 __weak typeof(self) weakSelf=self;
                 [QBRequest DoctorHospitalListWithDic:dic Success:^(id res)
                  {

                      if ([res[@"info"]count]==1)
                      {
                          [Util saveObjectToUserDefault:res[@"info"][0][@"id"] forKey:@"ShopId"];
                      }
                      else
                      {
                          [Util saveObjectToUserDefault:@"0" forKey:@"ShopId"];
                          
                      }
                      
                                       } failure:^(NSString *error)
                  {
                      
                  }];
                 
          NSString *auth_statusStr=infoDic[@"auth_status"];

          // 未认证
          if ([auth_statusStr isEqualToString:@"0"])
          {
              // 跳转到认证界面
           ConfirmVC *confirmVC=[ConfirmVC new];
           confirmVC.auth_statusStr=auth_statusStr;
           [weakSelf presentViewController:confirmVC animated:NO completion:nil];
          }
          //  认证中  认证成功  认证失败
          else
          {
             // 跳转认证信息界面
              ReviewVC *reviewVC=[ReviewVC new];
              reviewVC.auth_statusStr=auth_statusStr;
              [self presentViewController:reviewVC animated:NO completion:nil];
              
          }
             });
             
    
         } failure:^(NSString *error)
         {
             
         }];

    }
}

//开始连接服务器
- (void)startSDKService
{
    [self.view endEditing:YES];
    
    NSString *loginAccount = [Util getUserDefaultObjectForKey:@"accid"];
    NSString *loginToken   = [Util getUserDefaultObjectForKey:@"token"];

    [[[NIMSDK sharedSDK] loginManager] login:loginAccount token:loginToken completion:^(NSError *error) {
        
        [SVProgressHUD dismiss];
        
        if (error == nil){
            
            LoginData *sdkData = [[LoginData alloc] init];
            sdkData.account   = loginAccount;
            sdkData.token     = loginToken;
            
            [[NTESLoginManager sharedManager] setCurrentLoginData:sdkData];
            [[NTESServiceManager sharedManager] start];
            
        }
        else
        {
            [self.view makeToast:[NSString stringWithFormat:@"%ld",(long)error.code] duration:2.0 position:CSToastPositionCenter];
        }
        
    }];

}

@end


